package com.inventory.controller;

import com.inventory.model.Product;
import com.inventory.model.PurchaseRecord;
import com.inventory.model.User;
import com.inventory.service.ProductService;
import com.inventory.service.PurchaseRecordService;
import com.inventory.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("/purchases")
public class PurchaseController {

    @Autowired
    private PurchaseRecordService purchaseRecordService;
    
    @Autowired
    private ProductService productService;
    
    @Autowired
    private UserService userService;

    @GetMapping
    public String listPurchases(Model model,
                               @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
                               @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        
        LocalDateTime start = startDate != null ? startDate.atStartOfDay() : LocalDateTime.now().minusMonths(1);
        LocalDateTime end = endDate != null ? endDate.atTime(LocalTime.MAX) : LocalDateTime.now();
        
        model.addAttribute("purchases", purchaseRecordService.findByDateRange(start, end));
        model.addAttribute("startDate", startDate);
        model.addAttribute("endDate", endDate);
        model.addAttribute("totalAmount", purchaseRecordService.getTotalPurchaseAmount(start, end));
        
        return "purchase/list";
    }
    
    @GetMapping("/add")
    public String showAddForm(Model model, @RequestParam(required = false) Long productId) {
        PurchaseRecord purchaseRecord = new PurchaseRecord();
        
        // 如果指定了商品ID，则预先设置商品
        if (productId != null) {
            Optional<Product> productOpt = productService.findById(productId);
            if (productOpt.isPresent()) {
                Product product = productOpt.get();
                purchaseRecord.setProduct(product);
                purchaseRecord.setPrice(product.getPurchasePrice());
                purchaseRecord.setSupplier(product.getSupplier());
            }
        }
        
        model.addAttribute("purchaseRecord", purchaseRecord);
        model.addAttribute("products", productService.findActiveProducts());
        return "purchase/form";
    }
    
    @PostMapping("/add")
    public String addPurchase(@ModelAttribute PurchaseRecord purchaseRecord,
                             @RequestParam Long productId,
                             Authentication authentication,
                             RedirectAttributes redirectAttributes) {
        try {
            // 获取当前用户
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            Optional<User> userOpt = userService.findByUsername(userDetails.getUsername());
            
            if (!userOpt.isPresent()) {
                redirectAttributes.addFlashAttribute("error", "用户不存在");
                return "redirect:/purchases/add";
            }
            
            // 获取商品
            Optional<Product> productOpt = productService.findById(productId);
            
            if (!productOpt.isPresent()) {
                redirectAttributes.addFlashAttribute("error", "商品不存在");
                return "redirect:/purchases/add";
            }
            
            // 设置进货记录的用户和商品
            purchaseRecord.setUser(userOpt.get());
            purchaseRecord.setProduct(productOpt.get());
            
            // 如果没有设置批次号，自动生成一个
            if (purchaseRecord.getBatchNumber() == null || purchaseRecord.getBatchNumber().isEmpty()) {
                purchaseRecord.setBatchNumber(generateBatchNumber(productOpt.get()));
            }
            
            // 保存进货记录（同时会更新库存）
            purchaseRecordService.savePurchaseRecord(purchaseRecord);
            
            redirectAttributes.addFlashAttribute("success", "进货记录添加成功");
            return "redirect:/purchases";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "进货记录添加失败: " + e.getMessage());
            return "redirect:/purchases/add";
        }
    }
    
    @GetMapping("/detail/{id}")
    public String viewPurchaseDetail(@PathVariable Long id, Model model, RedirectAttributes redirectAttributes) {
        Optional<PurchaseRecord> purchaseOpt = purchaseRecordService.findById(id);
        
        if (!purchaseOpt.isPresent()) {
            redirectAttributes.addFlashAttribute("error", "进货记录不存在");
            return "redirect:/purchases";
        }
        
        PurchaseRecord purchase = purchaseOpt.get();
        model.addAttribute("purchase", purchase);
        
        // 获取同一商品的所有进货记录
        List<PurchaseRecord> productPurchases = purchaseRecordService.findByProductId(purchase.getProduct().getId());
        model.addAttribute("productPurchases", productPurchases);
        
        return "purchase/detail";
    }
    
    @GetMapping("/product/{productId}")
    public String viewProductPurchases(@PathVariable Long productId, Model model, RedirectAttributes redirectAttributes) {
        Optional<Product> productOpt = productService.findById(productId);
        
        if (!productOpt.isPresent()) {
            redirectAttributes.addFlashAttribute("error", "商品不存在");
            return "redirect:/products";
        }
        
        model.addAttribute("product", productOpt.get());
        model.addAttribute("purchases", purchaseRecordService.findByProductId(productId));
        return "purchase/product-purchases";
    }
    
    @GetMapping("/delete/{id}")
    public String deletePurchase(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            Optional<PurchaseRecord> purchaseOpt = purchaseRecordService.findById(id);
            
            if (!purchaseOpt.isPresent()) {
                redirectAttributes.addFlashAttribute("error", "进货记录不存在");
                return "redirect:/purchases";
            }
            
            // 删除进货记录（同时会减少库存）
            purchaseRecordService.deletePurchaseRecord(id);
            
            redirectAttributes.addFlashAttribute("success", "进货记录删除成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "进货记录删除失败: " + e.getMessage());
        }
        return "redirect:/purchases";
    }
    
    /**
     * 生成批次号
     * 格式：年月日-商品ID-4位随机数
     */
    private String generateBatchNumber(Product product) {
        LocalDate today = LocalDate.now();
        String dateStr = today.toString().replace("-", "");
        int randomNum = (int) (Math.random() * 10000);
        return String.format("BN-%s-%d-%04d", dateStr, product.getId(), randomNum);
    }
} 